package com.globallogic.log4j;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.FileAppender;
import org.apache.log4j.spi.ErrorCode;

public class NewLogForEachRunFileAppender extends FileAppender {

	@Override
	public void activateOptions() {
        
		if (null != fileName) {
			fileName = getNewFileName();
			try {
				setFile(fileName, fileAppend, bufferedIO, bufferSize);
			} catch (IOException e) {
				errorHandler.error("Error while activating log options", e,
		                ErrorCode.FILE_OPEN_FAILURE);			}
		}
		
	}
	
	private String getNewFileName(){

		if (null == fileName) {
			return null;			
		}
		
		final String DOT = ".";
		final String HIPHEN = "-";
		int dotPosition = fileName.indexOf(DOT);
		StringBuffer stringBuffer = new StringBuffer();
		DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy_hhmmss");
		Date now = Calendar.getInstance().getTime();
		
		
		if (dotPosition != -1) {
			stringBuffer.append(fileName.substring(0, dotPosition));
			stringBuffer.append(HIPHEN);
			stringBuffer.append(dateFormat.format(now));
			stringBuffer.append(DOT);
			stringBuffer.append(fileName.substring(dotPosition + 1));
		} else {
			stringBuffer.append(fileName);
			stringBuffer.append(HIPHEN);
			stringBuffer.append(dateFormat.format(now));
		}	
		
        return stringBuffer.toString();
	}
}
